/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package AssemblerUI;

import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

/**
 *
 * @author mahesh
 */
public class SymbolTable {
    
    public SymbolTable()
    {
        mapSymbols = new HashMap();
        mapSymbols.clear();
    }
    
    
    public void AddSymbol( String symbol, int address )
    {
        mapSymbols.put( symbol, new Integer(address) );
    }
    
    public int GetAddress( String symbol )
    {
        // returns the address if the symbol exists or -1 if it doesnt
        Integer index = mapSymbols.get(symbol);
        
        int retval = -1;
        if( index != null )
            retval = index.intValue();
        
        return retval;
    }
    
    public void Display()
    {
        for (Map.Entry<String, Integer> entry : mapSymbols.entrySet())
        {
            System.out.println(entry.getKey() + "/" + entry.getValue());
        }
    }
    
    public String GetSymbol( String instr )
    {
        String retval = "";
        
        StringTokenizer st2 = new StringTokenizer( instr, ":" );
            
        if( st2.countTokens() > 1 )
        {
            String symbol = st2.nextToken();
            System.out.println( "\t Symbol = " + symbol );

            retval = symbol;
        }
        return retval;
    }
    
    public String EliminateSymbol( String instr )
    {
        String retval ="";
        StringTokenizer st2 = new StringTokenizer( instr, ":" );
            
        if( st2.countTokens() > 1 )
        {
            st2.nextToken(); // just eliminate the first token
            
            retval = st2.nextToken();
            System.out.println( "\t Symbol = " + retval );
            
        }
        else
        {
            retval = st2.nextToken();
            System.out.println( "\t Symbol = " + retval );
        }
        
        return retval;
    }
    
    void GenerateSymbolTable( String strCode )
    {
        StringTokenizer st = new StringTokenizer( strCode, "\n" );
        
        int nLocationCounter = 0;
        
        
        while( st.hasMoreTokens() )
        {
            String instr = st.nextToken();
            System.out.println( "Instruction being assembled : " + instr );
            
            String symbol = GetSymbol(instr);
            if( symbol.equals("") == false )
            {
                AddSymbol(symbol, nLocationCounter);
            }
            
            nLocationCounter++;
        }
        Display();
    }
    
    private HashMap<String, Integer> mapSymbols;
    
}
